package com.pwl.shiro.realm;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import javax.security.auth.Subject;
import java.util.Arrays;
import java.util.List;

//自定义领域  extends AuthorizingRealm
public class CustomRealm extends AuthorizingRealm {
    @Override
    public String getName(){
        return "CustomRealm";
    }

     //授权器
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        //获取认证主体对象
        principalCollection.getPrimaryPrincipal();
        SimpleAuthorizationInfo authorizationInfo=new SimpleAuthorizationInfo();
        List<String> roles = Arrays.asList(new String[]{"线路管理员","消缺员","超级管理员"});
       roles.forEach(role->{
           authorizationInfo.addRole(role);
       });
       List<String> permissions=Arrays.asList(new String[]{"user:select","line:*"});
        permissions.forEach(permission->{
            authorizationInfo.addStringPermission(permission);
        });
       return authorizationInfo;
    }

    //认证器
    //以方法的形参存放着用户输入的密码和账号
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        //模拟数据库查询得到的账号密码
        String jdbcUsername="zhangsan";
        String jdbcPassword="123456";
        //手动判断
        if (!token.getPrincipal().toString().equals(jdbcUsername)){
            return null; //在此表示账号错误
        }

        return new SimpleAuthenticationInfo(token.getPrincipal(),jdbcPassword,getName());
    }


}
